<?php
/**
 * Created by ptmall
 * User :  河南邦耀科技有限公司
 * Date : 2020/9/2
 * Time : 13:51
 */

namespace app\api\controller;

use app\admin\model\activity\Tuangou;
use app\admin\model\order\Spell;
use app\admin\model\SpellOrder;
use app\common\controller\Api;
use app\common\model\Category;
use app\common\model\Config;
use fast\Random;
use fast\Tree;
use think\Db;
use think\Exception;
use think\Request;

class Order extends Api
{


    protected $noNeedRight = '*';

    protected $model = null;

    protected $newOrder = null;

    public function _initialize()
    {
        header("access-control-allow-headers:*");
        header("access-control-allow-methods:*");
        header("access-control-allow-origin:*");
        $this->model = new \app\admin\model\order\Order();
        parent::_initialize();
    }

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->model = new \app\admin\model\order\Order();
    }

    /**
     * @Explain :下单
     * @Date : 2020/9/4 15:22
     * @Author : 河南邦耀网络科技有限公司
     */
    public function create()
    {
        $userInfo = $this->auth->getUser();
        $fromUid = $this->request->request("fromUid", 0);
        $mobileRecharge = $this->request->request("mobileRecharge", 0);
        $addressId = $this->request->request("addressId", 1);
        $model = $this->request->request("model", false);
        $goods = $this->request->request("goods", '', 'urldecode');
        $goods = json_decode($goods, true);
        if (!$goods || !$model || !is_array($goods)) {
            $this->error('参数错误');
        }
        if (!$this->checkNum($userInfo->id)) {
            $this->success('下单过于频繁，请稍后再试！');
        }
        $address = Db::table('pt_address')->where(['id' => $addressId, 'uid' => $userInfo->id])->find();
        if ($mobileRecharge != 0) {
            $address = [
                'mobile' => $mobileRecharge,
                'username' => '',
                'address' => '',
                'province' => '',
                'city' => '',
                'district' => '',
            ];
        }
        if (empty($address)) $this->error('收货地址错误');
        $this->buildOrder($goods, $address, $model);
        $this->spellBuy($goods, $model);
    }

    /**
     * @Explain :创建订单
     * @param $goods
     * @param $address
     * @param $model
     * @Date : 2020/9/12 14:05
     * @Author : 河南邦耀网络科技有限公司
     */
    private function buildOrder($goods, $address, $model)
    {

        $orderPrice = $this->model->getSkuPrice($goods,$model);
        if(!$orderPrice && $model==3) $this->error('最多购买5份拼购商品');
        if(!$orderPrice) $this->error('商品信息错误');
        $goodsInfo = Db::table('pt_goods')->where(['goodsId' => $goods[0]['goodsId']])->find();
        $skuInfo = [];
        if (!empty($goods[0]['skuId'])) {
            $skuInfo = Db::table('pt_goods_skudetail')->where(['goodsId' => $goods[0]['goodsId'], 'skuId' => $goods[0]['skuId']])->find();
        }
        if ($model == 2) {
//          $orderPrice = bcmul($orderPrice, $discount * 0.01, 2);
            $goodsInfo['price'] = bcmul($goodsInfo['price'], $goodsInfo['discount'] * 0.01, 2);
            if (!empty($skuInfo)) {
                $goodsInfo['price'] = bcmul($skuInfo['price'], $goodsInfo['discount'] * 0.01, 2);
                $goodsInfo["image"] = !empty($skuInfo['image']) ? $skuInfo['image'] : $goodsInfo["image"];
            }
        } elseif ($model == 3) {
            $model = 3;
        } else {
            $discount = 100;
        }
        $order = [
            'uid' => $this->auth->id,
            'orderId' => time(),
            'goodsPrice' => $goodsInfo['price'],
            'goodsName' => $goodsInfo['title'],
            "skuName" => !empty($skuInfo) ? $skuInfo['title'] : "",
            "goodsNum" => $goods[0]['quantity'],
            'thumb' => $goodsInfo['image'],
            'goodsId' => $goodsInfo['goodsid'],
            'orderPrice' => $orderPrice,
            'payPrice' => $orderPrice,
            'ptid' => 0,
            'orderStatus' => 1,
            'username' => $address['username'],
            'mobile' => $this->auth->mobile,
            'addrmobile' => $address['mobile'],
            'address' => $address['address'],
            'province' => $address['province'],
            'city' => $address['city'],
            'district' => $address['district'],
            'discount' => $goodsInfo['discount'],
            "avatar" => $this->auth->avatar,
            'model' => $model,
            'createtime' => time(),
            "updatetime" => time(),
            'isApp'         =>$this->request->request('isApp',1),
            'channel'        =>$this->request->request('channel',0),
            'actid'        =>$this->request->request('actid',0),
        ];
        $this->newOrder = $order;
        return;
    }

    /**
     * @Explain :拼团购买
     * @param $orderId
     * @param $goods
     * @Date : 2020/9/12 16:38
     * @Author : 河南邦耀网络科技有限公司
     */

    private function spellBuy($goods, $model)
    {
        try {
            if ($model == 2) {
                $userSpellInfo = \app\admin\model\user\Spell::getInfo($this->auth->id);
                if (!empty($userSpellInfo)) {
                    $this->newOrder['ptid'] = $userSpellInfo['ptid'];
                    $this->newOrder['fromUid'] = $userSpellInfo['fromUid'];
                    $this->model->checkParentOrder($this->newOrder);
                }else {
                    $spellInfo = Spell::where(['uid' => $this->auth->getUser()->referee, 'isFinished' => 0, 'start' => 1])->order('id desc')->limit(6)->select();
                    foreach ($spellInfo as $row) {
//                        $spellInfo2 = Spell::get(['ptid' => $row['ptid'],'uid' => $this->auth->id]);
                        if (!empty($row)) {
                            $oldOrder = Spell::where(['uid' => $this->auth->id, 'ptid' => $row['ptid'], 'robot' => 0])->find();
                            if (!empty($oldOrder)) {
                                continue;
                            } else {
                                $this->newOrder['ptid'] = $row['ptid'];
                                $this->newOrder['fromUid'] = $this->auth->getUser()->referee;
                                break;
                            }
                        }
                    }
                }
            }

            if($model==3){
                $actInfo=Tuangou::get(['id'=>$this->request->request('actid',0)]);
                if($actInfo['status']!=1 || $actInfo['end_time']<time() || $actInfo['start_time']>time()){
                    $this->error('该期活动未开始或已完成，请更换其他活动');
                }
                if($actInfo['zcount']-$actInfo['pnum']<$this->newOrder['goodsNum']){
                    $this->error('超出该期活动剩余商品数量');
                }
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        Db::startTrans();
        try {
            $newId = $this->model->insert($this->newOrder, false, 1);
            $orderId = \fast\Utils::getOrderId("pt", $newId);
            $this->model->where('id', $newId)->update(['orderId' => $orderId]);
            $this->model->saveOrderdetail($this->auth->id, $orderId, $goods, $model);
            DB::commit();
            $pinggoodsovertime = \think\config::get("site.pinggoodsovertime");
            $this->success('ok', ['orderId' => $orderId, 'overtime' => $pinggoodsovertime * 60]);
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 获取参团总金额
     */
    public function pingPrice()
    {
        try {
            $userSpellInfo = \app\admin\model\user\Spell::where('uid', $this->auth->id)->where('status', 1)->order('id desc')->field('id,uid,ptid,fromUid')->find();
            $joinInfo = [];
            if (!empty($userSpellInfo) && $userSpellInfo['ptid'] > 0) {
                $joinInfo = \app\admin\model\spell\Spell::where('ptid', $userSpellInfo['ptid'])->where('start', 1)->find();
            }
            $price = $this->request->request("price", 0);
            $totalPrice = \app\admin\model\spell\Spell::getTotalPrice($price, $joinInfo);
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success("拼团总金额返回", ['totalPrice' => $totalPrice, "price" => $price]);
    }

    private function checkNum($uid)
    {
        $key = 'order_lock:' . $uid;
        if ($this->redis->exists($key)) {
            return false;
        } else {
            $this->redis->setex('order_lock:' . $uid, 6, '1');
        }
        return true;
    }

    public function cancelInfo(){
        $model = new \app\admin\model\SpellOrder();
        $orderId = $this->request->request("orderId",0);
        $orderInfo = $model->where('uid',$this->auth->id)->where('orderId',$orderId)->find();
        if(empty($orderInfo) || !in_array($orderInfo->orderStatus,[1,2])){
            $this->error("订单信息获取失败");
        }
        if($orderInfo->orderStatus ==2){//已支付退款
            $return = \app\admin\model\spell\Refund::getRules($orderInfo);
        }
        $day = \think\config::get("site.pingorderreturnday");
        $this->success("返回取消比例",$return);

    }

}
